#include "Line.h"

#include <QPainter>
#include <QColor>
#include "../Settings/GameSettings.h"

Line::Line(Dot *p1,Dot *p2,Game::Player owner):QLine(p1->point(),p2->point()), mp1(p1), mp2(p2), mOwner(owner)
{
}

Game::Player Line::owner(){return mOwner;}

bool Line::nearToMe(QPoint pos)
{
    return this->p1() == pos || this->p2() == pos;
}

bool Line::hozizontal()
{
    return mp1->y() == mp2->y();
}

Dot *Line::dot1()const{return mp1;}
Dot *Line::dot2()const{return mp2;}

void Line::draw(QPainter *pDC)
{
    pDC->setPen(GameSettings::me()->pen(owner()));
    pDC->drawLine(mp1->point(),mp2->point());
}

QLine Line::line(){return QLine(mp1->point(),mp2->point());}

bool Line::isSame(QLine line1, QLine line2)
{
    return ((line1.p1() == line2.p1()) && (line1.p2() == line2.p2())) ||
            ((line1.p1() == line2.p2()) && (line1.p2() == line2.p1()));
}

bool Line::isSame(QLine line)
{
    return Line::isSame(line,this->line());
}

bool Line::isSame(Element *pElem, bool bByValue)
{
    Line *pLine = dynamic_cast<Line*>(pElem);

    if(pLine){
        if(bByValue){
            return isSame(this->line(),pLine->line());
        }
        else{
            return this == pLine;
        }
    }
    else{
        return false;
    }
}

bool Line::isMyContainer(Cell *pCell)
{
    for(int i = 0; i < mContainerCells.count(); i++){
        if(mContainerCells.at(i) == pCell){
            return true;
        }
    }

    return false;
}

bool Line::addContainer(Cell *pCell)
{
    if(!isMyContainer(pCell)){
        mContainerCells.append(pCell);
        mp1->addContainerCell(pCell);
        mp2->addContainerCell(pCell);
        mp1->addContainerLine(this);
        mp2->addContainerLine(this);

        return true;
    }

    return false;
}

bool Line::removeContainer(Cell *pCell)
{
    for(int i = 0; i < mContainerCells.count(); i++){
        if(mContainerCells.at(i) == pCell){
            mp1->removeContainerCell(pCell);
            mp2->removeContainerCell(pCell);
            mp1->removeContainerLine(this);
            mp2->removeContainerLine(this);
            mContainerCells.removeOne(pCell);
            return true;
        }
    }

    return false;
}

int Line::containerCount(){return mContainerCells.count();}
